package com.haishuibutian.rocketmqconsumer.rocketmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

@Component
public class MQConsumerProcessor implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(MQConsumerProcessor.class);

    @Resource
    private MQListener mqListener;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("开始扫描MQ消费处理器...");
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(MQConsumerComponent.class);
        logger.info("扫描到MQ消费处理器 -> {}", Arrays.asList(beanNames));
        for (String beanName : beanNames) {
            Class<?> clazz = applicationContext.getBean(beanName).getClass();
            MQConsumerComponent consumerComponent = AnnotationUtils.findAnnotation(clazz, MQConsumerComponent.class);
            String tags = consumerComponent.tags();
            mqListener.registerHandler(tags, applicationContext.getBean(beanName, MQConsumerHandler.class));
            logger.info("'{}' 注册到MQ消费者成功", beanName);
        }
    }
}
